import { h, render } from 'vue';
import VIcon from '@/components/Icon.vue';
import { VNodeDirective } from '@/interface/types/vnode';
import { isObject } from '@/utils';

const createIcon: (o: any, a: any) => Node = (options, attributes) => {
  const container = document.createElement('div');
  let instance: any = null;
  if (isObject(options)) {
    instance = h(VIcon, options);
  } else {
    instance = h(VIcon, { icon: options });
  }
  render(instance, container, true);
  
  /* 设置属性 */
  [...attributes].forEach(attr => {
    if (!attr.name.includes('data-v')) {
      container.firstElementChild?.setAttribute(attr.name, attr.value); 
    }
  });
  return container;
}

const mounted = (el: HTMLElement, binding: VNodeDirective) => {
  if (binding.value) {
    const parent = el.parentNode;
    const attributes = el.attributes;
    // 创建元素
    const newNode = createIcon(binding.value, attributes);
    (parent as Node).insertBefore(newNode, el);
    (parent as Node).removeChild(el);
  }

}

export const Icon = {
  mounted
}